package io.gitee.zhangbinhub.admin.workflow.service

import com.mybatisflex.core.query.QueryWrapper
import io.gitee.zhangbinhub.admin.resource.server.vo.ProcessInstanceVo
import io.gitee.zhangbinhub.admin.workflow.base.BaseService
import io.gitee.zhangbinhub.admin.workflow.entity.MyProcessInstance
import io.gitee.zhangbinhub.admin.workflow.repo.MyProcessInstanceRepository
import org.dromara.warm.flow.core.entity.Instance
import org.noear.solon.annotation.Component
import org.noear.solon.data.annotation.Transaction

@Component
open class MyProcessInstanceService(
    private val myProcessInstanceRepository: MyProcessInstanceRepository,
) : BaseService() {
    @Transaction
    fun addMyProcessInstance(userId: String, instance: Instance, processInstanceVo: ProcessInstanceVo) {
        myProcessInstanceRepository.selectListByQuery(
            QueryWrapper.create().where(MyProcessInstance::userId).eq(userId)
                .and(MyProcessInstance::processInstanceId).eq(instance.id)
        ).let {
            if (it.isEmpty()) {
                myProcessInstanceRepository.insert(
                    MyProcessInstance(
                        processInstanceId = instance.id,
                        processDefinitionKey = processInstanceVo.processDefinitionKey!!,
                        businessKey = instance.businessId,
                        startUserId = processInstanceVo.startUser?.id,
                        userId = userId,
                        startTime = processInstanceVo.startTime
                    )
                )
            }
        }
    }
}